package com.example.springbootdemo.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootdemo.aspect.HttpAspect;
import com.example.springbootdemo.base.BaseResult;
import com.example.springbootdemo.bean.User;
import com.example.springbootdemo.bean.Security;
import com.example.springbootdemo.http.SSLSocketClient;
import com.example.springbootdemo.mapper.SecurityMapper;
import com.example.springbootdemo.service.UserSevice;
import com.example.springbootdemo.utils.*;

import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserSevice mUserSevice;
    @Resource
    LogUtil mLogger;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    SecurityMapper mMapper;

    @PostMapping("add")
    public BaseResult addRedis() throws Exception {
        List<String> strings = new ArrayList<>();
        strings.add("a");
        strings.add("b");
        strings.add("c");
        strings.add("c1");
        strings.add("c4");

        redisUtil.remove("age");
        redisUtil.setData("age", strings);
        return ResultUtil.success();
    }

    @GetMapping("login")
    public BaseResult login(@RequestParam("username") String usename, @RequestParam("password") String password) throws Exception {
        Thread.sleep(2000);
        BaseResult result = new BaseResult();
        if (usename.equals("admin") && password.equals("123")) {
            result.setCode(0);
            result.setMessage("");
            result.setData("登陆成功");
        } else {
            result.setCode(1);
            result.setMessage("账号或密码错误");
            result.setData("");
        }
        return result;
    }

    @GetMapping("/file")
    @ResponseBody
    public void file(HttpServletResponse response) {

//        //定义保存的文件
//        String filePath = "d://测试.xlsx";
//
//        //设置列名
//        List<String> head = Arrays.asList("姓名", "年龄", "地址");
//
//        //组装数据
//        List<List<Object>> data = new ArrayList<>();
//        data.add(Arrays.asList("111", "222", "333"));
//        data.add(Arrays.asList("111", "222", "333"));
//        data.add(Arrays.asList("111", "222", "333"));
////        //写入数据
//        ExcelExport.writeBySimple(filePath, data, head);
//
//        //下载并删除源文件
//        ExcelExport.downloadExcel(filePath, "下载的名字.xlsx", response);
    }

    @GetMapping("/templete")
    public void templete(HttpServletResponse response) {
        try {
            //1、定义模板路径
            String templatePath = "D:\\template.xlsx";
            //2、定义导出路径
            String exportPath = "D:\\test.xlsx";
            //3、组装数据
            Map<String, Object> data = new HashMap<>();
            User user = new User();
            user.setYear("2019");
            user.setMonth("11");
            user.setDay("05");
            user.setName("哈药六厂");
            user.setUsername("杨顺岭");
            user.setPhone("18058810112");
            user.setAddress("浙江省杭州市滨江区智汇中心B座15楼");
            user.setCallback("所有产品都期望用户可以积极的投入参与产品，毕竟只有用户投入，产品才有存在的价值。每个人都有自己的观点，所以无论以什么形式从用户那里征求意见，都是使用户参与到交流当中最简单的方式之一。给予反馈也被认为是使用户参与进来的最低门槛之一，通常也是大部分产品必备的功能之一。通过产生的反馈进行数据分析，用来改变和调整给用户呈现的内容，改进内容与用户体验的质量。");
            user.setAbc1(JxlsUtils.symbol(true));
            user.setAbc2(JxlsUtils.symbol(false));
            data.put("user", user);
            //4、导出Excel
            JxlsUtils.exportByPath(templatePath, exportPath, data);
            //5、下载并删除Excel
            JxlsUtils.downloadExcel(exportPath, "报表导出.xlsx", response);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @PostMapping("/uploadFiles")
    @ResponseBody
    public String uploadFiles(HttpServletRequest request) throws IOException {

        String filePath = "D:\\file";

        File savePath = new File(filePath);
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    File saveFile = new File(savePath, file.getOriginalFilename());
                    stream = new BufferedOutputStream(new FileOutputStream(saveFile));
                    stream.write(bytes);
                    stream.close();
                    //记录文件
                    LoggerFactory.getLogger(HttpAspect.class).info("文件上传路径：" + filePath + "\\" + ((MultipartHttpServletRequest) request).getFile("file").getName());
                } catch (Exception e) {
                    if (stream != null) {
                        stream.close();
                        stream = null;
                    }
                    return "第 " + i + " 个文件上传有错误" + e.getMessage();
                }
            } else {
                return "第 " + i + " 个文件为空";
            }
        }
        return "所有文件上传成功";
    }

    @PostMapping(value = "pdf")
    public void getFile() throws IOException {
        int page = 0;
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .build();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new JSONObject().toString());
        for (int i = 0; i < 7882; i++) {
            Request request = new Request.Builder()
                    .url("https://gs.amac.org.cn/amac-infodisc/api/pof/fund?rand=0.6538189557866072&page=" + page + "&size=20")
                    .post(requestBody)
                    .build();
            Response response = okHttpClient.newCall(request).execute();
            Security b = JSON.parseObject(response.body().string(), Security.class);
            for (int j = 0; j < b.getContent().size(); j++) {

                Security.ContentBean contentBean = b.getContent().get(j);
                if (StringUtils.isNotBlank(contentBean.getEstablishDate())) {
                    String establishDate = contentBean.getEstablishDate();
                    String s = DataUtil.stampToDate(establishDate);
                    contentBean.setEstablishDate(s);
                }
                if (StringUtils.isNotBlank(contentBean.getPutOnRecordDate())) {
                    String putOnRecordDate = contentBean.getPutOnRecordDate();
                    String ss = DataUtil.stampToDate(putOnRecordDate);
                    contentBean.setPutOnRecordDate(ss);
                }
                mMapper.insert(contentBean);
            }
            System.out.println("第" + (page + 1) + "页插入完成");
            page++;
        }
    }
}
